package cc.comac.mom.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cc.comac.mom.api.EquipSparePartsTypeService;
import cc.comac.mom.bean.EquipSparePartsType;
import cc.comac.mom.bean.ResultDev;
import cc.comac.mom.datahandlers.entity.EquipSparePartMasterDataDataHandler;
import cc.comac.mom.datahandlers.entity.EquipSparePartsTypeDataHandler;
import cc.comac.mom.entity.EquipSparePartMasterDataEntity;
import cc.comac.mom.entity.EquipSparePartsTypeEntity;
import cc.comac.mom.util.ExcelUploadUtil;
import cc.comac.mom.util.ExportExcel;
import cc.comac.mom.util.ResultBean;

@RestController
@Service
public class EquipSparePartsTypeServiceImpl implements EquipSparePartsTypeService {

	@Autowired
	private EquipSparePartsTypeDataHandler equipSpareSartsTypeDataHandler;

	@Autowired
	private EquipSparePartMasterDataDataHandler equipSparePartMasterDataDataHandler;

	@Override
	public ResultBean save(@RequestBody EquipSparePartsType obj) {
		// TODO Auto-generated method stub
		return equipSpareSartsTypeDataHandler.save(obj);
	}

	@Override
	public ResultBean update(@RequestBody EquipSparePartsType obj) {
		// TODO Auto-generated method stub
		return equipSpareSartsTypeDataHandler.update(obj);
	}

	@Override
	public EquipSparePartsType getById(@RequestBody EquipSparePartsType obj) {
		// TODO Auto-generated method stub
		return equipSpareSartsTypeDataHandler.getById(obj.getInnerData().getId());
	}

	@Override
	public ResultDev selectByCondition(@RequestBody EquipSparePartsType obj) {
		ResultDev resultDev = new ResultDev();
		if (obj.getSearchAll() != 1) {
			resultDev = equipSpareSartsTypeDataHandler.selectByCondition(obj);
		} else {
			resultDev = equipSpareSartsTypeDataHandler.selectByCondition(obj);
		}
		return resultDev;
	}

	@Override
	public ResultBean deleteBatch(@RequestBody List<EquipSparePartsType> list) {
		ResultBean resultBean = new ResultBean(true);
		ArrayList<Long> listIds = new ArrayList<Long>();
		for (EquipSparePartsType item : list) {
			if (item.getInnerData() != null) {
				listIds.add(item.getInnerData().getId());
			}
		}
		Collection<EquipSparePartsTypeEntity> listByIds = equipSpareSartsTypeDataHandler.listByIds(listIds);
		if (listByIds == null || listByIds.size() < 1) {
			resultBean.setSuccess(false);
			resultBean.setMessage("数据不存在");
			return resultBean;
		}

		for (EquipSparePartsTypeEntity item : listByIds) {
			QueryWrapper<EquipSparePartMasterDataEntity> queryWrapper = new QueryWrapper<EquipSparePartMasterDataEntity>();
			queryWrapper.eq("row_status", 1);
			queryWrapper.eq("spare_part_type", item.getCategoryName());
			List<EquipSparePartMasterDataEntity> list2 = equipSparePartMasterDataDataHandler.list(queryWrapper);
			if (list2 != null && list2.size() > 0) {
				resultBean.setSuccess(false);
				resultBean.setMessage("备件类型:" + item.getCategoryName() + " 被备件主数据引用，不可删除");
				return resultBean;
			}
		}
		return equipSpareSartsTypeDataHandler.deleteBatch(list);
	}

	@Override
	public ResultBean getAllEnable() {
		ResultBean resultBean = new ResultBean(true);
		ResultDev resultDev = equipSpareSartsTypeDataHandler.getAllEnable();
		resultBean.setObject(resultDev);
		return resultBean;
	}

	@Override
	public ResultBean importSparePartsType(@RequestPart("file") MultipartFile file, @RequestParam String rootPath)
			throws IOException {
		ResultBean resultBean = new ResultBean(true);
//		if (file == null || file.isEmpty()) {
//			resultBean.setSuccess(false);
//			resultBean.setMessage("上传失败，请重新上传！");
//			return resultBean;
//		} else if (file.getSize() > 10000000) {
//			resultBean.setSuccess(false);
//			resultBean.setMessage("上传失败，文件大小不能超过10M!！");
//			return resultBean;
//		}
//
//		String fileName = file.getOriginalFilename();
//		File dir = new File(rootPath);
//		if (!dir.exists()) {
//			dir.mkdir();
//		}
//		File chunkFile = new File(dir, fileName);
//		try {
//			chunkFile.createNewFile();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		file.transferTo(chunkFile);

		ArrayList<String> listTypeNum = new ArrayList<String>();
		ArrayList<String> listTypeName = new ArrayList<String>();
		ArrayList<String> listError = new ArrayList<String>();
		ArrayList<EquipSparePartsTypeEntity> listNewTypeEntity = new ArrayList<EquipSparePartsTypeEntity>();
		QueryWrapper<EquipSparePartsTypeEntity> queryWrapper = new QueryWrapper<EquipSparePartsTypeEntity>();
		queryWrapper.eq("row_status", 1);
		List<EquipSparePartsTypeEntity> listEquipSparePartsTypeEntity = equipSpareSartsTypeDataHandler
				.list(queryWrapper);
		if (listEquipSparePartsTypeEntity != null && listEquipSparePartsTypeEntity.size() > 0) {
			for (EquipSparePartsTypeEntity item : listEquipSparePartsTypeEntity) {
				listTypeNum.add(item.getCategoryNumber());
				listTypeName.add(item.getCategoryName());
			}
		}
		try {
//			InputStream in = file.getInputStream();
//			FileInputStream in = new FileInputStream(chunkFile);
			Workbook workbook;
			try {
				workbook = ExcelUploadUtil.getWorkBook(file);
				// Sheet的数量
				int sheetCount = workbook.getNumberOfSheets();
				// 循环sheet
				for (int i = 0; i < sheetCount; i++) {
					Sheet sheetAt = workbook.getSheetAt(i);
					// 行数
					int rowCount = sheetAt.getLastRowNum();
					System.out.println(rowCount + "行数");
					if (rowCount < 1) {
						continue;
					}
					// 循环行
					for (int j = 1; j <= rowCount; j++) {
						Row row = sheetAt.getRow(j);
						Cell cell0 = row.getCell(0);
						Object categoryNumber = ExcelUploadUtil.getValue(cell0);
						if (categoryNumber == null) {
							continue;
						}
						if (listTypeNum.contains(categoryNumber)) {
							continue;
						}
						Cell cell1 = row.getCell(1);
						Object categoryName = ExcelUploadUtil.getValue(cell1);
						if (categoryName == null) {
							continue;
						}
						if (listTypeName.contains(categoryName)) {
							continue;
						}
						Cell cell2 = row.getCell(2);
						Object remark = ExcelUploadUtil.getValue(cell2);
						Cell cell3 = row.getCell(3);
						Object enable = ExcelUploadUtil.getValue(cell3);
						if (enable == null) {
							continue;
						}
						if (!"0".equals(enable.toString()) && !"1".equals(enable.toString())) {
							if (enable.toString().contains("是") || enable.toString().contains("启用")) {
								enable = 1;
							} else if (enable.toString().contains("否") || enable.toString().contains("不")) {
								enable = 0;
							} else {
								continue;
							}

						}
						EquipSparePartsTypeEntity typeEntity = new EquipSparePartsTypeEntity();
						typeEntity.setCategoryNumber(categoryNumber.toString());
						typeEntity.setCategoryName(categoryName.toString());
						typeEntity.setRemark(remark.toString());
						typeEntity.setEnable(Integer.valueOf(enable.toString()));
						listNewTypeEntity.add(typeEntity);
						listTypeNum.add(categoryNumber.toString());
						listTypeName.add(categoryName.toString());
					}

				}
//				chunkFile.delete();
				return equipSpareSartsTypeDataHandler.importBatch(listNewTypeEntity);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
//		chunkFile.delete();
		return resultBean;
	}

	@Override
	public String exportData(HttpServletRequest request, HttpServletResponse response,
			@RequestBody EquipSparePartsType obj) throws IOException {
		List<EquipSparePartsTypeEntity> list = equipSpareSartsTypeDataHandler.exportSelectByCondition(obj);
		String[] rowsName = new String[] { "类型编码", "类型名称", "备注", "是否启用", "创建人", "创建时间", "修改人", "修改时间", "预留" };
		List<Object[]> dataList = new ArrayList<Object[]>();
		for (int i = 0; i < list.size(); i++) {
			Object[] objs = new Object[rowsName.length];// 创建13个数组长度
			EquipSparePartsTypeEntity partsTypeEntity = list.get(i);
			objs[0] = partsTypeEntity.getCategoryNumber();
			objs[1] = partsTypeEntity.getCategoryName();
			objs[2] = partsTypeEntity.getRemark();
			if (partsTypeEntity.getEnable() == 1) {
				objs[3] = "是";
			} else {
				objs[3] = "否";
			}
			objs[4] = partsTypeEntity.getCreator();
			objs[5] = partsTypeEntity.getCreationTime();
			objs[6] = partsTypeEntity.getLastModifier();
			objs[7] = partsTypeEntity.getLastModifiedTime();
			objs[8] = "";
			dataList.add(objs);
		}

		String fileName = "备件类型";
		// 执行导出
		String filePath = ExportExcel.exportExcel(request, response, fileName, rowsName, dataList,
				"yyyy-MM-dd HH:mm:ss");

		// String resu = response.toString();
		return filePath;
	}
}
